package com.easymin.weixin.service.impl;

import com.easymin.weixin.entity.Admin;
import com.easymin.weixin.entity.AdminCriteria;
import com.easymin.weixin.mapper.AdminMapper;
import com.easymin.weixin.mapper.BaseMapper;
import com.easymin.weixin.service.AdminService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * Created by shine on 15/8/19.
 */
@Service
public class DefaultAdminService extends AbstractBaseService<Admin, AdminCriteria, Long> implements AdminService {

  @Autowired
  private AdminMapper adminMapper;

  @Override
  public BaseMapper<Admin, AdminCriteria, Long> getMapper() {

    return adminMapper;
  }

  @Override
  public int insert(Admin admin) {

    admin.setCreated(new Date());
    admin.setUpdated(new Date());
    admin.setVersion(1);
    return super.insert(admin);
  }

  @Override
  public boolean exists(String username) {

    AdminCriteria adminCriteria = new AdminCriteria();
    adminCriteria.createCriteria().andUsernameEqualTo(username);

    long total = adminMapper.countByExample(adminCriteria);

    return total > 0;
  }

  @Override
  public int update(Admin admin) {

    admin.setUpdated(new Date());
    return super.update(admin);
  }

  @Override
  public Admin findByUsername(String username) {

    AdminCriteria adminCriteria = new AdminCriteria();
    adminCriteria.createCriteria().andUsernameEqualTo(username);

    List<Admin> admins = adminMapper.selectByExample(adminCriteria);

    if (!CollectionUtils.isEmpty(admins)) {
      return admins.get(0);
    }

    return null;
  }
}
